package middleware

import (
	"net/http"

	"goweb/ext/app"
	"goweb/ext/e"
	"goweb/ext/jwt"
	"goweb/ext/settings"
	"goweb/service/auth"
	"goweb/utils/commons"
	"goweb/utils/redis"

	"github.com/gin-gonic/gin"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		appG := app.Gin{C: c}
		//cookie涉及到跨域问题
		token := c.Query("token")

		if token == "" {
			appG.CheckResponse(http.StatusOK, e.INVALID_PARAMS, nil)
			return
		} else {
			claims, err, flag := jwt.ParseToken(token)
			//claims含有用户信息
			if err != nil {
				appG.CheckResponse(http.StatusOK, flag, nil)
				return
			}
			uid := claims.Uid
			if _, err := redis.GetValue(commons.StringJoin([]string{conf.PERX_TOKEN, uid, "_", claims.SourceId}), conf.RDb1); err != nil {
				appG.CheckResponse(http.StatusOK, e.ERROR_TOKEN, nil)
				return
			}
			uri := c.Request.URL.Path
			code := auth.CheckPer(uid, uri)
			if code != e.SUCCESS {
				appG.CheckResponse(http.StatusOK, code, nil)
				return
			}

		}

		c.Next()
	}
}
